package com.xiang.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiang.pojo.User;
import com.xiang.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/9/26 21:00
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServiceImpl userServiceImpl;

//    @GetMapping("/list")
//    public String queryAllUser(Model model) {
//        List<User> users = userServiceImpl.queryAllUser();
//        model.addAttribute("users", users);
//        return "list";
//    }

    //查询所有并分页显示
    @GetMapping("/list")
    public String queryAllUser(@RequestParam(value = "page", defaultValue = "1") Integer page, Model model){
        //获取指定页数据，每页显示8条数据
        PageHelper.startPage(page, 6);
        //紧跟的第一个select方法被分页
        List<User> users = userServiceImpl.queryAllUser();
        model.addAttribute("users",users);
        //使用PageInfo包装数据 navigatePages表示导航标签的数量
        PageInfo pageInfo = new PageInfo(users, 5);
        model.addAttribute("pageInfo", pageInfo);
        return "list";
    }



    @PostMapping("/add")
    public String addUser(User user) {
        int i = userServiceImpl.addUser(user);
        return "redirect:/user/list";  // redirect 重定向/跳转
    }

    @GetMapping("/queryUserById/{id}")
    public String queryUserById(@PathVariable("id") Integer id, Model model) {
        User user = userServiceImpl.queryUserById(id);
        model.addAttribute("user",user);
        return "update";  //转发（默认为）
    }

    @PostMapping("/update")
    public String queryUserById(User user) {
        int i = userServiceImpl.updateUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        int i = userServiceImpl.deleteUser(id);
        return "redirect:/user/list";
    }

    @GetMapping("/conditionQuery")
    public String deleteUser(User user,Model model) {
        List<User> users = userServiceImpl.conditionQuery(user);
        model.addAttribute("users",users);
        return "list";
    }

}

